const jwt = require('jsonwebtoken')

const secret = process.env.SECRET
const expiresIn = process.env.EXPIRES_IN

module.exports = {
  sign: ({ id, jwtid }) => {
    return new Promise((resolve, reject) => {
      jwt.sign({ id }, secret, { expiresIn, jwtid }, (error, token) => {
        if (error) {
          reject(error)
        }
        resolve(token)
      })
    })
  },
  verify: ({ token, jwtid }) => {
    return new Promise((resolve, reject) => {
      jwt.verify(token, secret, { jwtid }, (error, decoded) => {
        if (error) {
          reject(error)
        }
        resolve(decoded)
      })
    })
  },
  getTypeFields: type => {
    if (type && type['_fields']) {
      const fields = {}
      // const fields = []
      for (let i in type['_fields']) {
        fields[i] = type['_fields'][i].description
        // fields.push([i, type['_fields'][i].description])
      }
      return JSON.stringify(fields)
      // return fields
    }
    return null
  },
  getUser: token => {
    if (token) {
      // invalid token - synchronous
      try {
        const id = jwt.verify(token, secret)
        return { id }
      } catch (err) {
        // err
        // 验证失败处理
        console.log(err)
        return null
      }
    }
    return null
  }
}
